import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;

public abstract class Customer implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;
    public static ArrayList<Customer> customers = new ArrayList<>();
    public static HashMap<String,String> hsmp = new HashMap<>();
    private static int ID=100000;
    protected boolean pwd = false;//判断是否登录成功，设计一个循环，每次判断一次
    protected int ID1;
    protected String Name;
    protected String time;
    protected String type;
    protected String telephoneNumber;
    protected String password;
    protected boolean once = false;
    public Customer(int ID1,String Name,String telephoneNumber,String password,String time) {
        this.ID1=ID1;
        this.Name=Name;
        this.telephoneNumber=telephoneNumber;
        this.password=password;
        this.time=time;
        hsmp.put(this.Name, String.valueOf(this.ID1));
        customers.add(this);
        saveCustomerInfo();
    }
    public Customer(String name, String type, String telephoneNumber, String password) {
        this.ID1 = Customer.ID++;
        this.Name = name;
        this.time =  LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        this.type = type;
        this.telephoneNumber = telephoneNumber;
        this.password = password;
        hsmp.put(this.Name, String.valueOf(this.ID1));
        customers.add(this);
        saveCustomerInfo();
    }
    public void setType(String type) {
        this.type = type;
    }
    private void saveCustomerInfo() {
        try (PrintWriter pw = new PrintWriter(new FileWriter("CustomerNum.txt", true))) {
            pw.println(ID1 + " " + Name + " " + type + " " + telephoneNumber);
            System.out.println("已记录在客户信息文件中");
        } catch (IOException e) {
            System.out.println("无法写入客户信息文件: " + e.getMessage());
        }
    }
    protected static void logAction(String action) {
        try (PrintWriter pw = new PrintWriter(new FileWriter("log.txt", true))) {
            pw.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
                    + " " + action);
        } catch (IOException e) {
            System.out.println("无法写入日志文件: " + e.getMessage());
        }
    }
    public static void saveCustomersToFile(String filePath) throws IOException {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath))) {
            oos.writeObject(customers);
            oos.writeInt(ID);
            System.out.println("客户数据已保存到文件: " + filePath);
        } catch (IOException e) {
            System.out.println("保存客户数据失败: " + e.getMessage());
        }
    }
    @SuppressWarnings("unchecked")
    public static void loadCustomersFromFile(String filePath) throws IOException{
        File file = new File(filePath);
        if(file.exists()){
            try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath))) {
                customers = (ArrayList<Customer>) ois.readObject();
                ID = ois.readInt();
                hsmp.clear();
                for (Customer c : customers) {
                    hsmp.put(c.Name, String.valueOf(c.ID1));
                }
            } catch (ClassNotFoundException e) {
                System.out.println("加载客户数据失败: " + e.getMessage());
            }

        }
        else{
            System.out.println("数据文件不存在，将创建新文件");
        }
    }
    public  void logout(){
        System.out.println("logout");
        this.pwd = false;
    }

    protected void changeOnce() {
        this.once=false;
    }
}
class Manager extends Customer {
    @Serial
    private static final long serialVersionUID = 1L;
    private static Manager Admin = null;
    transient Scanner in = new Scanner(System.in);
    protected boolean DA = false;//DA是用来判断是不是admin管理员
    private  boolean once = false;
    public Manager(String Name,String telephoneNumber,String password) {
        super(Name,"Manager",telephoneNumber,password);
    }
    public Manager(String Name,String telephoneNumber) {
        this(Name,telephoneNumber,"123456");
    }
    public boolean getOnce(){
        if(this.DA){
            return true;
        }
        return once;
    }
    public static Manager getAdmin() {
        if (Admin == null) {
            for (Customer c : customers) {
                if (c instanceof Manager && ((Manager) c).DA) {
                    Admin = (Manager) c;
                    System.out.println("从文件加载Admin实例: " + Admin.Name);
                    return Admin;
                }
            }
            // 如果没有，则创建新的Admin
            Admin = new Manager("admin", "18_596_371_173", "ynuinfo#777");
            Admin.DA = true;
            System.out.println("创建新的Admin实例");
        }
        return Admin;
    }
    public Customer login(int Id, String pw){
        Customer ct = null;
        for (Customer c : customers) {
            if (c.ID1 == Id && c.password.equals(pw)&&c instanceof Manager) {
                c.pwd = true;
                logAction(c.type + c.Name + " logged in");
                ct=c;
            }
        }
        if(this.password.equals(Admin.password)&&this.Name.equals(Admin.Name)){
            this.DA = true;
        }
        return ct;
    }
    public void addPeople(Scanner in){
        System.out.println("输入类型：");
        String type = in.nextLine();
        System.out.println("输入名称：");
        String name1=in.nextLine();
        System.out.println("输入电话号码：");
        String telephoneNumber1=in.nextLine();
        switch(type){
            case "Manager":
                if (DA) {
                    Manager m = new Manager(name1, telephoneNumber1);
                    System.out.println("添加管理员成功: " + m.ID1 + " " + m.Name);
                } else {
                    System.out.println("您没有权限添加管理员");
                }
                break;
            case "Director":
                Director director = new Director(name1,telephoneNumber1,"123456");
                System.out.println("添加导演成功: " + director.ID1 + " " + director.Name);
                break;
            case "Stage":
                Stage stage = new Stage(name1,telephoneNumber1,"123456");
                System.out.println("添加舞台工作人员成功: " + stage.ID1 + " " + stage.Name);
                break;
            default:
                System.out.println("error");
        }
    }
    public void showPeople(){
        for(Customer c:Customer.customers) {
            if(!(c instanceof Manager)){
                System.out.println(c.ID1+" "+c.Name+" "+c.type+" "+c.time+" "+c.telephoneNumber);
            }
            else {
                continue;
            }
        }
    }
    public void searchPeople(Scanner in){
        System.out.println("请选择输入名称或姓名或直接搜索全部人信息");
        System.out.println("1.姓名\n2.ID\n3.全部人信息");
        int num=in.nextInt();
        switch(num){
            case 1:
                System.out.println("请输入名字：");
                in.nextLine();
                String name1=in.nextLine();
                for(Customer c:customers) {
                    if(c.Name.equals(name1)&&!c.Name.equals("admin")){
                        System.out.println(c.ID1+" "+c.Name+" "+c.type+" "+c.time+" "+c.telephoneNumber);
                    }
                }
                break;
            case 2:
                System.out.println("请输入id：");
                int id=in.nextInt();
                for(Customer c:customers) {
                    if(c.ID1==id&&!c.Name.equals("admin")){
                        System.out.println(c.ID1+" "+c.Name+" "+c.type+" "+c.time+" "+c.telephoneNumber);
                    }
                }
                break;
            case 3:
                showPeople();
                break;
            default:
                System.out.println("error");
                break;
        }
    }
    public void removeCustomer(Scanner in) {
        boolean deleted = false;
        System.out.println("您确定要删除用户吗? (yes/no)");
        String confirm = in.nextLine(); // 先读取整行
        int a = 0;
        if (confirm.equalsIgnoreCase("yes")) {
            System.out.println("请输入要删除的ID");
            int j = in.nextInt();
            a=j;
            in.nextLine(); // 消耗换行符
            Iterator<Customer> iterator = customers.iterator();
            while (iterator.hasNext()) {
                Customer c = iterator.next();
                if (c.ID1 == j) {
                    switch (c.type) {
                        case "Manager":
                            if (DA) { // 只有Admin有权删除Manager
                                iterator.remove(); // 用迭代器删除，而非customers.remove(c)
                                hsmp.remove(c.Name); // 更新映射
                                deleted = true;
                            } else {
                                System.out.println("不是Admin,无权删除Manager");
                                return;
                            }
                            break;
                        default:
                            iterator.remove(); // 迭代器删除
                            hsmp.remove(c.Name);
                            deleted = true;
                            System.out.println("meiyou");
                            break;
                    }
                    break;
                }
            }
        } else {
            System.out.println("返回上一页");
        }
        if (!deleted) {
            System.out.println("未找到ID为" + a + "的用户");
        } else {
            System.out.println("用户删除成功");
        }
    }

    public void alterSelfPassword(String password){
        this.password=password;
        logAction("修改manager密码"+" "+this.Name);
        this.once=true;
    }
    public void resetOtherPassword(int Id){
        for(Customer c:customers) {
            if(c.ID1==Id&&!(c instanceof Manager)){
                c.password= String.valueOf(123456);
                c.changeOnce();
                logAction(c.type+c.Name);
            }
        }
    }
    public void changeMassage(Scanner in){
        System.out.println("请选择要修改的人的id：");
        int id = in.nextInt();
        in.nextLine();
        Customer cu=null;
        for(Customer c:customers) {
            if(c.ID1==id){
                cu=c;
            }
        }
        if (cu == null) {
            System.out.println("未找到该用户");
            return;
        }

        if ("Manager".equals(cu.type)) {
            System.out.println("不能修改管理员信息");
            return;
        }
        System.out.println("请输入要修改的内容：");
        System.out.println(("1.用户类型\n2.用户电话号码"));
        int num=in.nextInt();
        in.nextLine();
        String oldTime = cu.time;
        switch (num){

            case 1:
                if(cu.type.equals("director")){
                    Stage stage = new Stage(cu.ID1,cu.Name,cu.telephoneNumber,cu.password,cu.time);
                    stage.setType("Stage");
                    customers.remove(cu);
                    hsmp.remove(cu.Name);
                }
                else{ Director director = new Director(cu.ID1, cu.Name, cu.telephoneNumber, cu.password,cu.time);
                    director.time = oldTime; // 恢复原始注册时间
                    director.setType("director"); // 明确设置类型
                    customers.remove(cu);
                    hsmp.remove(cu.Name);
                }
                System.out.println("用户类型修改成功");
                break;
            case 2:
                System.out.println("请输入新的电话号码");
                cu.telephoneNumber=in.nextLine();
                break;
            default:
                System.out.println("error");
                break;
        }

    }
}
class Director extends Customer {
    @Serial
    private Plan plan=new Plan();
    private static final long serialVersionUID = 1L;
    transient Scanner in = new Scanner(System.in);
    Sale sale=new Sale();
    public Director(String Name,String telephoneNumber,String password) {
        super(Name,"director",telephoneNumber,password);
    }
    public Director(int ID,String Name,String telephoneNumber,String password,String time) {
        super(ID,Name,telephoneNumber,password,time);
    }
    public  void changeSelfPassword(String password){
        this.password=password;
        this.once=true;
        this.type = "director";
    }
    public boolean getOnce(){
        return once;
    }
    public void resetOtherPassword(Scanner in){
        System.out.println("请输入要修改的ID：");
        int Id= in.nextInt();
        for(Customer c:customers) {
            if(c.ID1==Id&&c instanceof Stage){}
            c.password="123456";
            logAction("Director " + Name + " reset password for stage staff " + Id);
        }
    }
    public static Customer login(int Id, String pw) {
        for (Customer c : customers) {
            // 修复：检查是否为Director类型
            if (c.ID1 == Id && c.password.equals(pw) && c instanceof Director) {
                c.pwd = true; // 设置登录状态
                logAction(c.type + " " + c.Name + " logged in");
                return c; // 返回实际的Director对象
            }
        }
        return null;
    }
    public void changeFilm(Scanner in){
        System.out.println("要修改的电影");
        String Title = in.nextLine();
        for (Film film : Plan.films) {
            if (film.getTitle().equals(Title)) {
                System.out.println("请输入新电影名");
                String title = in.nextLine();
                film.setTitle(title);
                System.out.println("请输入新导演");
                String Author = in.nextLine();
                film.setAuthor(Author);
                System.out.println("请输入新主演");
                String Star = in.nextLine();
                film.setStar(Star);
                System.out.println("请输入新情节");
                String Plot = in.nextLine();
                film.setPlot(Plot);
                System.out.println("请输入新时长");
                int DurationMinutes = in.nextInt();
                film.setDurationMinutes(DurationMinutes);
                System.out.println("请输入新评级");
                int Grade = in.nextInt();
                film.setGrade(Grade);
                System.out.println("请输入新电影票价");
                int money = in.nextInt();
                film.setMoney(money);
            }
        }
    }
    public void deleteFilm(Scanner in) {
        // 修复1：提示文本错误（删除用户→删除电影）
        System.out.println("您确定要删除电影吗? (yes/no)");
        if (in.nextLine().equalsIgnoreCase("yes")) {
            System.out.println("请选择要删除的电影");
            String Title = in.nextLine();

            // 修复2：使用迭代器遍历，避免ConcurrentModificationException
            Iterator<Film> iterator = Plan.films.iterator();
            boolean found = false;

            while (iterator.hasNext()) {
                Film film = iterator.next();
                if (film.getTitle().equals(Title)) {
                    found = true;
                    // 检查电影是否已排期
                    if (film.isOnBoard()) {
                        System.out.println("该电影已排期，无法删除");
                        return; // 已排期则直接返回
                    }
                    // 修复3：用迭代器删除，而非集合删除
                    iterator.remove();
                    System.out.println("电影删除成功");
                    break; // 找到并删除后退出循环
                }
            }

            // 修复4：添加未找到电影的提示
            if (!found) {
                System.out.println("未找到该电影");
            }
        } else {
            System.out.println("返回上一页");
        }
    }

    public void searchFilm(Scanner in){
        System.out.println("请输入电影名");
        String Title = in.nextLine();
        for (Film film : Plan.films) {
            if (film.getTitle().equals(Title)) {
                film.message();
            }
        }
    }
    public void addFilm(Scanner in) {
        System.out.println("请输入影片信息:");
        System.out.println("Title:");
        String Title = in.nextLine();
        System.out.println("Author:");
        String Author = in.nextLine();
        System.out.println("Star:");
        String Star = in.nextLine();
        System.out.println("Plot :");
        String Plot = in.nextLine();
        System.out.println("Duration:");
        int DurationMinutes = in.nextInt();
        System.out.println("Grade:");
        int Grade = in.nextInt();
        System.out.println("Money:");
        int money = in.nextInt();
        Film film = new Film(Title,Author,Star,Plot,DurationMinutes,Grade,money);
        Plan.films.add(film);
    }
    public void showFilm() {
        for (Film film : Plan.films) {
            film.message();
        }
    }
    private ArrayList<LocalDateTime> notScheduledTime(Screenroom screenroom) {
        ArrayList<LocalDateTime> nst = new ArrayList<>();
        ArrayList<LocalDateTime> times = plan.generateCandidateTimes(7, 30);

        // 先获取该放映厅已有的所有排片时间
        Set<LocalDateTime> scheduledTimes = new HashSet<>();
        for (Session session : Plan.sessions) {
            if (session.getScreen().equals(screenroom)) {
                scheduledTimes.add(session.getStartTime());
            }
        }

        // 遍历所有候选时间，找出未排片的时间
        for (LocalDateTime time : times) {
            if (!scheduledTimes.contains(time)) {
                nst.add(time);
            }
        }

        return nst;
    }
    public void addSession(Scanner in) {
        System.out.println("请输入要排序的电影名");
        String Title = in.nextLine();
        Film film=null;
        for (Film films : Plan.films) {
            if (films.getTitle().equals(Title)) {
                film=films;
            }
        }
        System.out.println("请输入要排序的电影厅的名字");
        System.out.println("所有放映厅列表：");
        Screenroom[] screenrooms = Screenroom.values();
        for (int i = 0; i < screenrooms.length; i++) {
            System.out.printf("[%d] %s\n", i + 1, screenrooms[i].getRoomName());
        }
        String screen = in.nextLine();
        Screenroom screenroom=Screenroom.getByRoomName(screen);
        ArrayList<LocalDateTime> nst = notScheduledTime(screenroom);
        if (nst.isEmpty()) {
            System.out.println("没有可用的排片时间！");
            return;
        }
        System.out.println("请选择排片时间（输入序号）：");
        for (int i = 0; i < nst.size(); i++) {
            System.out.printf("[%d] %s\n", i + 1, nst.get(i).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
        }
        int choice = -1;
        while (choice < 1 || choice > nst.size()) {
            System.out.print("请输入序号：");
            try {
                choice = in.nextInt();
                in.nextLine(); // 清空输入缓冲区
            } catch (Exception e) {
                System.out.println("输入无效，请重新输入数字！");
                in.nextLine(); // 清除错误输入
            }
        }
        LocalDateTime selectedTime = nst.get(choice - 1);
        // 校验该时间在当前放映厅是否可用（避免并发冲突）
        if (screenroom.isAvailable(film, selectedTime)) {
            Session session = new Session(film, screenroom, selectedTime);
            Plan.sessions.add(session);
            screenroom.addSession(session); // 同步添加到放映厅
        } else {
            System.out.println("该时间在当前放映厅已被占用，请重新选择！");
        }
    }
    public void changeSession(Scanner in) {
        System.out.println("请输入要修改的电影名");
        String Title = in.nextLine();
        Film film=null;
        for (Film films : Plan.films) {
            if (films.getTitle().equals(Title)) {
                film=films;
            }
        }
        System.out.println("请输入要修改的电影厅");
        String screen = in.nextLine();
        Screenroom screenroom=Screenroom.getByRoomName(screen);
        System.out.println("请输入要修改的时间段");
        LocalDateTime showTime = TimeConverter.inputToLocalDateTime("请输入场次开始时间");
        Session session= sale.searchSession(film,showTime,screenroom);
        if(!session.isqA()){
            System.out.println("1.替换为其他电影\n2.空场");
            int choice = in.nextInt();
            switch (choice) {
                case 1:
                    System.out.println("请输入要改变为什么电影");
                    in.nextLine();
                    String title=in.nextLine();
                    for(Film films : Plan.films) {
                        if (films.getTitle().equals(title)) {
                            session.setFilm(films);
                        }
                    }
                    break;
                case 2:
                    session.setFilm(null);
                    break;
            }
            logAction("Film " + session.getFilm() + " changed session");
        }
        else{
            System.out.println("已售出票，不可修改");
        }
    }
    public void deleteSession(Scanner in) {
        System.out.println("请输入要删除的电影名");
        String Title = in.nextLine();
        Film film = null;
        // 查找电影（添加未找到判断）
        for (Film films : Plan.films) {
            if (films.getTitle().equals(Title)) {
                film = films;
                break; // 找到后退出循环
            }
        }
        if (film == null) {
            System.out.println("未找到该电影");
            return;
        }

        System.out.println("请输入要删除的电影厅");
        String screen = in.nextLine();
        Screenroom screenroom = Screenroom.getByRoomName(screen);
        // 检查影厅是否存在
        if (screenroom == null) {
            System.out.println("未找到该影厅");
            return;
        }

        System.out.println("请输入要删除的场次开始时间");
        LocalDateTime showTime = TimeConverter.inputToLocalDateTime("请输入场次开始时间");
        Session session = sale.searchSession(film, showTime, screenroom);
        // 检查场次是否存在
        if (session == null) {
            System.out.println("未找到该场次");
            return;
        }

        // 修复逻辑：已售出票（isqA()为true）则不可删除，反之可删除
        if (!session.isqA()) {
            // 使用迭代器删除，避免潜在的ConcurrentModificationException
            Iterator<Session> iterator = Plan.sessions.iterator();
            while (iterator.hasNext()) {
                if (iterator.next().equals(session)) {
                    iterator.remove();
                    break;
                }
            }
            logAction("Film " + session.getFilm() + " deleted session");
            System.out.println("场次删除成功");
        } else {
            System.out.println("已售出票，不可删除");
        }
    }

    public void arrangeSession() {
        plan.arrangeFilms();
    }
    public void showSession(Scanner in){
        int day;
        System.out.println("是否要修改为查看其他时间段:yse/no");
        String yn=in.nextLine();
        if(yn.equals("yes")){
            System.out.println("请输入要查看的时间");
            day=in.nextInt();
        }
        else{
            day = 7;
        }
        LocalDateTime date = LocalDateTime.now().plusDays(day);
        for(Session session: Plan.sessions){
            if(session.getStartTime().isBefore(date)){
                System.out.printf("电影：%s，时间：%s，影厅：%s%n",
                        session.getFilm(),
                        session.getStartTime().format(TimeConverter.FORMATTER), // 用系统格式显示时间
                        session.getScreen().getRoomName());
            }
        }
    }
    public void searchDayTicket(){
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = LocalDateTime.now().minusDays(1);
        double sum=0;
        double resum=0;
        Session session1=null;
        for(Session session:Plan.sessions){
            if(session.getStartTime().isAfter(startTime)&&session.getEndTime().isBefore(endTime)){
                sum+=session.getTicketNum()*session.getCurrentMoney();
                System.out.print(session.getFilm()+session.getScreenRoom()+session.getStartTime().toString()+session.getTicketNum()+session.getCurrentMoney()+session.getReTicket()+session.getReTicket()*session.getCurrentMoney());
            }
        }
        System.out.println(sum);
    }
    public void searchWeekTicket(Scanner in){
        System.out.println("请选择要查看一周还是一月");
        int t=0;
        String time=in.nextLine();
        if(time.equals("week")){
            t=7;
        }
        else{
            t=30;
        }
        double allTicket=0,allSellMoney=0,allReTicket=0,allReSellMoney=0,sum=0;
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = LocalDateTime.now().minusDays(t);
        for(Session session:Plan.sessions){
            if(session.getStartTime().isAfter(startTime)&&session.getEndTime().isBefore(endTime)){
                allSellMoney+=session.getTicketNum()*session.getCurrentMoney();
                allReSellMoney+=session.getReTicket()*session.getCurrentMoney();
                allReTicket+=session.getReTicket();
                allTicket+=session.getTicketNum();
                sum=allSellMoney-allReSellMoney;
            }
        }
        System.out.println(allTicket+allSellMoney+allReTicket+allReSellMoney+sum);
    }
}
class Stage extends Customer {
    @Serial
    private static final long serialVersionUID = 1L;
    transient Scanner in = new Scanner(System.in);
    Plan plan=new Plan();
    Sale sale=new Sale();
    public Stage(String Name, String telephoneNumber, String password) {
        super(Name,"Stage",telephoneNumber,password);
    }
    public Stage(int ID,String Name,String telephoneNumber,String password,String time) {
        super(ID,Name,telephoneNumber,password,time);
        this.type = "director";
    }
    public void showFilm(){
        for(Film film:Plan.films){
            film.message();
        }
    }
    public void changeSelfPassword(String password){
        this.password=password;
    }
    public boolean getOnce(){
        return once;
    }
    public void setOnce(boolean once) {
        this.once = once;
    }
    public void showSession(){
        for(Session session:Plan.sessions){
            System.out.printf("电影：%s，时间：%s，影厅：%s%n",
                    session.getFilm(),
                    session.getStartTime().format(TimeConverter.FORMATTER),
                    session.getScreen().getRoomName());
        }
    }
    public static Customer login(int Id, String pw) {
        for (Customer c : customers) {
            // 修复：检查是否为Stage类型
            if (c.ID1 == Id && c.password.equals(pw) && c instanceof Stage) {
                c.pwd = true; // 设置登录状态
                logAction(c.type + " " + c.Name + " logged in");
                return c;
            }
        }
        return null;
    }
    private Session searchSessions(Scanner in) {
        System.out.println("请输入要查看的电影名：");
        String title = in.nextLine().trim();
        if (title.isEmpty()) {
            System.out.println("电影名不能为空");
            return null;
        }
        Film film = null;
        for (Film f : Plan.films) {
            if (f.getTitle().equals(title)) {
                film = f;
                break;
            }
        }
        if (film == null) {
            System.out.println("未找到名为《" + title + "》的电影");
            return null;
        }
        System.out.println("请输入要查看的电影厅：");
        String screenName = in.nextLine().trim();
        if (screenName.isEmpty()) {
            System.out.println("影厅名不能为空");
            return null;
        }
        Screenroom screenroom = Screenroom.getByRoomName(screenName);
        if (screenroom == null) {
            System.out.println("未找到名为《" + screenName + "》的影厅");
            return null;
        }
        System.out.println("请输入要查看的场次开始时间：");
        String timeInput = TimeConverter.inputTimeString("请输入场次开始时间");
        LocalDateTime showTime = null;

        try {
            showTime = LocalDateTime.parse(timeInput, TimeConverter.FORMATTER);
        } catch (DateTimeParseException e) {
            System.out.println("时间格式错误，使用当前时间代替");
            showTime = LocalDateTime.now();
        }

        Session session = sale.searchSession(film, showTime, screenroom);
        if (session == null) {
            System.out.println("未找到对应场次（电影：《" + title + "》，影厅：" +
                    screenName + "，时间：" + showTime + "）");
        }
        return session;
    }
    private Session searchSessions(String title, String screenName,LocalDateTime localDateTime) {
        Film film = null;
        for (Film f : Plan.films) {
            if (f.getTitle().equals(title)) {
                film = f;
                break;
            }
        }
        if (film == null) {
            System.out.println("未找到名为《" + title + "》的电影");
            return null;
        }
        Screenroom screenroom = Screenroom.getByRoomName(screenName);
        Session session = sale.searchSession(film, localDateTime, screenroom);
        if (session == null) {
            System.out.println("未找到对应场次（电影：《" + title + "》，影厅：" +
                    screenName + "，时间：" + localDateTime + "）");
        }
        return session;
    }
    public void showChair(Scanner in) {
        Session session = searchSessions(in);
        if (session == null) {
            System.out.println("未找到对应场次，无法显示座位");
            return;
        }
        int rows = session.getScreen().row;    // 行数（如10行）
        int cols = session.getScreen().column; // 列数（如8列）
        for (int i = 0; i <=rows; i++) {
            for (int j = 0; j <= cols; j++) {
                if (i == 0 && j == 0) {
                    System.out.print("  ");
                } else if (i == 0) {
                    System.out.print(j + " ");
                } else if (j == 0) {
                    System.out.print(i + " ");
                } else {
                    if (session.getSeat(i-1,j-1)) {
                        System.out.print("O ");
                    } else {
                        System.out.print("X ");
                    }
                }
            }
            System.out.println();
        }
    }
    public void chooseChairs(Scanner in){
        System.out.println("=== 当前可用场次 ===");
        for (int i = 0; i < Plan.sessions.size(); i++) {
            Session s = Plan.sessions.get(i);
            System.out.printf("[%d] %s | %s | %s%n",
                    i + 1,
                    s.getFilm(),
                    s.getScreen().getRoomName(),
                    s.getStartTime().format(DateTimeFormatter.ofPattern("MM/dd HH:mm"))
            );
        }

        System.out.print("请选择场次编号: ");
        int choice = in.nextInt();
        in.nextLine(); // 消耗换行符

        if (choice < 1 || choice > Plan.sessions.size()) {
            System.out.println("无效选择");
            return;
        }
        Session session = Plan.sessions.get(choice - 1);
        int r = -1, c = -1, x = -1;
        try {
            System.out.println("请输入行号：");
            r = in.nextInt();
            System.out.println("请输入起始列号：");
            c = in.nextInt();
            System.out.println("需要连续几张票：");
            x = in.nextInt();
            in.nextLine();
        } catch (InputMismatchException e) {
            System.out.println("输入错误！行、列和票数必须是整数");
            in.nextLine();
            return;
        }
        Screenroom screen = session.getScreen();
        if (screen == null) {
            System.out.println("影厅信息无效");
            return;
        }
        if (r < 0 || r >= screen.row ||
                c < 0 || c >= screen.column ||
                x <= 0 || (c + x) > screen.column) {
            System.out.println("座位范围无效！请检查输入（行：0-" + (screen.row-1) +
                    "，列：0-" + (screen.column-1) + "，票数：至少1张）");
            return;
        }

        sale.chooseChair(session, r, c, x);
        System.out.println("当前票价：" + session.getCurrentMoney());
    }
    public void deleteChairs(Scanner in) {
        System.out.println("请输入电子票ID：");
        String id = in.nextLine();
        Session session = null;
        int r=-1, c=-1;
        for(Ticket ticket:Sale.tickets){
            if(ticket.getTicketId().equals(id)){
                session=searchSessions(ticket.getFilmTitle(), ticket.getScreenRoom(), ticket.getStartTime());
                r=ticket.getRow();
                c=ticket.getColumn();
            }
        }
        if (session.getStartTime().isAfter(LocalDateTime.now().plusHours(1))) {
            sale.deleteChair(session, r, c);
            LocalDateTime oneDayBefore = LocalDateTime.now().minusDays(1);
            if (session.getStartTime().isBefore(oneDayBefore)) {
                sale.setMoney(session.getCurrentMoney() * 0.9, false); // 10%手续费
            } else {
                sale.setMoney(session.getCurrentMoney(), false); // 全额退款
            }
        } else {
            System.out.println("距离开场不足1小时，无法退票");
        }
    }
}


